package com.client;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.db.connection.DBCPPostgresManager;
import com.db.domain.Record;
import com.excel.read.Config;
import com.operation.OperationMap;
import com.service.CommunicationService;
import com.service.ImportService;
import com.service.RecordCreateServiceClient;
import com.service.SyncService;
import com.service.SyncServiceFactory;
import com.xml.ExtractFactory;
import com.xml.RecordExtract;


/**
 * 
 * @功能 根据本地的记录(sync)复制远程节点所需的记录(record) 一个本地记录要被复制到所有其他节点
 * @author 张华
 * @date May 24, 2009
 * @version 1.0  May 24, 2009 2:43:03 PM
 */
public class RecordCreateService implements Runnable {
	static Log log = LogFactory.getLog(RecordCreateService.class);
	public static long orgid = getStoreID();
	// 线程运行的时间间隔，当遇到异常时时间间隔调大，并给以警告，正常时调小
	public static final int timeNormal = 1000;
	public static final int timeERR = 20000;
	public static int dltTime = timeNormal;

	public static List<Long> list = new ArrayList<Long>();

	/**
	 * 将Postgres的同步记录copy中央服务器
	 * 
	 * @return
	 */
	public static long copyRecord() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {

			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn
					.prepareStatement("select * from ad_sync where flag = 'N'");

			rs = pstmt.executeQuery();
			int size = 0;

			while (rs.next()) {
				size++;
				String content = rs.getString("content");
				Record record = new Record();
//				record.setContent("TODO");
				record.setCreated(rs.getString("created"));
				record.setFlag("N");
				record.setContent(content);
				record.storeFrom = rs.getLong("store_id");
				String fullContrent  = null;
				// 重组Content
				if(ExtractFactory.isPO(record.content)) {
					RecordExtract aRecordExtract = new RecordExtract();
					OperationMap aOperationMap = (OperationMap)aRecordExtract
							.extractOperationMap(content, record.storeFrom);
					fullContrent = aOperationMap.getHTML();
				}else {
					fullContrent = record.content;
				}
				
				
				record.setContent(fullContrent);
				SyncService aSyncService = SyncServiceFactory.getSyncService();
				for (long id : list) {
					// 对每一个店
					if (id != orgid) {
						aSyncService.clientToServer(orgid, id, record);
					}
				}
				doneRecord(rs.getLong("id"));
				// 事务结束
				dltTime = timeNormal;

			}
			if (size > 0) {
				log.info("OK:" + size);				
			}
		} catch (Exception ex) {
			dltTime = timeERR;

			System.out.println("Error-RecordCreateService: " + ex);
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);
		}
		return 0;
	}

	public static long doneRecord(Long id) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {
			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			pstmt = conn
					.prepareStatement("update ad_sync set flag = 'Y' where id = ? ");
			pstmt.setLong(1, id);
			pstmt.executeUpdate();
			pstmt.getConnection().commit();

		} catch (Exception ex) {
			System.out.println("Error : " + ex.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return 0;
	}

	/**
	 * 取得所有分店
	 * 
	 * @return
	 * @throws SQLException
	 */
	private static void getStore() throws SQLException {
		long id = 0;
		Connection conn = null;
		// 加载Connector/J驱动
		try {
			conn = DBCPPostgresManager.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 执行SQL语句
		String sql = "select AD_ORG_ID from ad_org";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				id = rs.getLong("ad_org_id");
				list.add(id);
			}
		} catch (Exception e) {

			
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);
		}

	} // fillCombos

	private static long getStoreID() {
		long id = 0;
		Connection conn = null;
		// 加载Connector/J驱动
		try {
			conn = DBCPPostgresManager.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 执行SQL语句
		String sql = "select org_id from ad_current_store where id = 1";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				id = rs.getLong(1);
			}
		} catch (Exception e) {

		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return id;

	}

	public Record getRecord() {
		Record aRecord = null;

		return aRecord;
	}

	/**
	 * @param args
	 */
	public static void main(String args[]) {		
		Config.generateTable("c:\\table_config.xls");
		log.info("数据同步开始。");
		// 数据传输
		Thread clientSide = new Thread(new RecordCreateService());
		Thread clientSide2 = new Thread(new RecordCreateServiceClient());
		// 数据导入
		Thread importThread = new Thread(new ImportService());
		//数据的请求与响应
		Thread communicationThread = new Thread(new CommunicationService());
		
		//客户端对客户端
		
		clientSide.start();
		clientSide2.start();
		importThread.start();
		communicationThread.start();
		
		
	}

	public void run() {

		try {
			getStore();
			while (true) {
				copyRecord();
				Thread.currentThread().sleep(dltTime);
				// System.out.println("next2...");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
}
